from rest_framework.viewsets import ModelViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework.decorators import action
import pandas as pd
from .models import *
from .serializers import *
# from .userfilter import UserFilter

# Create your views here.
class RolesViewset(ModelViewSet):
    queryset = Roles.objects.all()
    serializer_class = RolesSerializers

class UserViewset(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializers

    @action(methods=['post','get'],detail=False)
    def adduser(self,request):
        data = request.data
        user = User.objects.create_user(username=data['username'],password=data['password'])
        return Response({'mess':'创建成功！'})

    @action(methods=['post',],detail=False)
    def importUser(self,request,*args,**kwargs):
        # 接受前端传来的文件
        rev_file = request.FILES.get('file')
        # 判断文件是否为空
        if not rev_file:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 数据处理
        data = pd.read_excel(rev_file,sheet_name=0,header=1,names=['id','username','first_name','last_name','password'])
        data = data.fillna('')
        row_len = len(data)
        if row_len == 0:
            return Response({'status':False,'error':'你没有输入数据！'})
        else:
            errors = []
            for i in range(row_len):
                user_tem = data.iloc[i]
                try:
                    User.objects.get(username=user_tem.username)
                    errors.append({'error':'你导入的数据%s已经存在。'%user_tem.username})
                except Exception:
                    User.objects.create_user(username=user_tem.username,password=user_tem.password,
                        first_name=user_tem.first_name,last_name=user_tem.last_name)
        return Response({'status':True,'data':'数据导入成功','errors':errors})

class MenuViewset(ModelViewSet):
    queryset = Menu.objects.all()
    serializer_class = MenuSerializers

    @action(methods=['post','get'],detail=False)
    def teuser(self,request):
        print(request.user.password)
        return Response({'data':'成功'})

class RolesUserViewset(ModelViewSet):
    queryset = RolesUser.objects.all()
    serializer_class = RolesUserSerializers

    def update(self,request,*args,**kwargs):
        try:
            data = request.data
            roleuser = RolesUser.objects.get(user=data['user'])
            roleuser.role.set(data['role'])
            roleuser.save()
        except :
            pass
        return Response({'status':200})

    @action(methods=['get',],detail=False)
    def refreshUser(self,request):
        users = User.objects.all()
        role = Roles.objects.get(name='tourist')
        for user in users:
            try:
                roleuser = RolesUser.objects.get(user=user)
            except Exception:
                roleUser = RolesUser.objects.create(user=user)
                roleUser.role.set([role,])
                roleUser.save()
        return Response({'status':True})

class PermissionViewset(ModelViewSet):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializers

    @action(methods=['post','get'],detail=False)
    def menus(self,request):
        roleuser = RolesUser.objects.filter(user=request.user).first()
        roles = roleuser.role.all()
        # 去二级菜单重
        menus_tem = set([])
        for role in roles:
            for menus in role.roles.all():
                menus_tem.add(menus)
        # 变成Json格式
        twomenujsons = []
        for twomenu in menus_tem:
            twomenujsons.append({
                'title':twomenu.title,
                'name':twomenu.name,
                'url':twomenu.url,
                'component':twomenu.component,
                'icon':twomenu.icon,
                'order':twomenu.order,
                'menu':twomenu.menu.title
                })
        # 一级菜单去重
        onemenu = set([])
        for tem in menus_tem:
            onemenu.add(tem.menu)
        # 一级菜单Json格式化
        onemenujsons = []
        for menu in onemenu:
            json = {
            "title":menu.title,
            "icon":menu.icon,
            "order":menu.order,
            "twomenus":[]
            }
            onemenujsons.append(json)
            # 返回前端相要的json
        for twomenujson in twomenujsons:
            for onemenujson in onemenujsons:
                if onemenujson['title']==twomenujson['menu']:
                    onemenujson['twomenus'].append(twomenujson)
        return Response(onemenujsons)